import { IDesignDataItem, readDesignData, saveDesignData } from '@/appUtils/appData/designData'
import { defineStore } from 'pinia'
import { ref, toRaw } from 'vue'
import { useWorkSpaceStore } from './workSpace'

// 设计稿数据
export const useDesignStore = defineStore('design', () => {
    // json数据
    const designData = ref<IDesignDataItem[]>([])

    const getWorkSpaceId = () => {
        const workSpaceData = useWorkSpaceStore()
        const { data } = workSpaceData
        if (!data) {
            return
        }
        return data.id
    }

    // 初始化
    const init = async () => {
        const workSpaceId = getWorkSpaceId()

        if (!workSpaceId) return
        const readedData = await readDesignData(workSpaceId)
        designData.value = readedData
    }

    // 保存
    const save = async (newData: IDesignDataItem[]) => {
        const workSpaceId = getWorkSpaceId()
        if (!workSpaceId) {
            return '未选择工作空间'
        }
        await saveDesignData({
            workSpaceId,
            data: toRaw(newData)
        })
    }

    // 当捕获到新的数据时
    const handleCapturedData = async (data: IDesignDataItem) => {
        const { id } = data
        const index = designData.value.findIndex((item) => item.id === id)
        let type: 'add' | 'update' = 'add'
        // 之前有
        if (index > -1) {
            // 如果存在则替换
            designData.value[index] = data
            type = 'update'
        } else {
            // 之前没有，添加进去
            designData.value.push(data)
        }
        await save(designData.value)
        console.log('保存成功')
        return type
    }

    return {
        designData,
        handleCapturedData,
        init
    }
})
